package com.fsgom.common.web.freemarker;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;

import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
import freemarker.template.TemplateException;

public class TemplateMaker {
	private String root = "";
	private Class<?> clazz = this.getClass();
	private final String template;
	private final Map<String, Object> contextRoot = new HashMap<String, Object>();

	public TemplateMaker(String root, String template) {
		this.root = root;
		this.template = template;
	}

	public TemplateMaker(Class<?> clazz, String template) {
		this.clazz = clazz;
		this.template = template;
	}

	private Template getTemplate() throws IOException {
		Configuration configuration = new Configuration();
		configuration.setClassForTemplateLoading(clazz, root);
		configuration.setObjectWrapper(new DefaultObjectWrapper());
		return configuration.getTemplate(template, "UTF-8");
	}

	public void setAttribute(String key, Object value) {
		contextRoot.put(key, value);
	}

	public void removeAttribute(String key) {
		contextRoot.remove(key);
	}

	public String process() throws TemplateException, IOException {
		OutputStream outputStream = new ByteArrayOutputStream();
		Writer writer = new OutputStreamWriter(outputStream);
		getTemplate().process(contextRoot, writer);
		writer.flush();

		return outputStream.toString();
	}
}
